515. Find Largest Value in Each Tree Row - LeetCode Solution


Tree BFS

Python Code:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def largestValues(self, root: TreeNode) -> List[int]:
        q = [root, None]
        
        count = 0
        
        ans =  []
        s = []
        
        while len(q) != 0:
            k = q.pop(0)
            
            if k== None:
                count+=1
                
                if count == 2:
                    break
                else:
                    
                    if len(s) != 0:
                        ans.append(max(s))
                    s = []
                    
                    q.append(None)
                    
                continue
            count = 0
            if k.right:
                q.append(k.right)
                
            if k.left:
                q.append(k.left)
                
            s.append(k.val)
            
        
        return ans
                
        


Comments

Submit
0 Comments
More Questions

429A - Xor-tree
1675C - Detective Task
950A - Left-handers Right-handers and Ambidexters
672B - Different is Good
1C - Ancient Berland Circus
721A - One-dimensional Japanese Crossword
1715B - Beautiful Array
60B - Serial Time
453A - Little Pony and Expected Maximum
1715A - Crossmarket
1715C - Monoblock
1512C - A-B Palindrome
1679B - Stone Age Problem
402A - Nuts
792A - New Bus Route
221A - Little Elephant and Function
492C - Vanya and Exams
1369B - AccurateLee
892B - Wrath
999A - Mishka and Contest
727C - Guess the Array
1625C - Road Optimization
1715D - 2+ doors
267A - Subtractions
1582A - Luntik and Concerts
560A - Currency System in Geraldion
946A - Partition
1068B - LCM
1692E - Binary Deque
679A - Bear and Prime 100